﻿using System;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;
using System.IO;
using Core;

namespace Desktop
{
    /// <summary>
    /// Interaction logic for Key.xaml
    /// </summary>
    public partial class Key : UserControl
    {
        public string Text
        {
            get
            { return textBox.Text; }
            set
            { textBox.Text = value; }
        }

        private string fileFilter;
        public string FileFilter
        {
            get { return fileFilter; }
            set { fileFilter = value; }
        }

        public Key()
        {
            InitializeComponent();

            // Init file filter
            this.fileFilter = "All Files|*.*";
        }

        private void buttonOpen_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = fileFilter;
            ofd.RestoreDirectory = true;
            String fileName = null;

            // Show Open File Dialog
            if (ofd.ShowDialog() == true)
            {
                fileName = ofd.FileName;
                if (fileName != null)
                {
                    // read file
                    readFile(fileName);
                }
            }
        }

        private void readFile(string fileName)
        {
            // Make File Stream
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

            // Create temporary
            long length = fs.Length;
            byte[] temp = new byte[length];

            // Read File
            fs.Position = 0;
            fs.Read(temp, 0, (int)length);

            // Set stream
            MemoryStream stream = new MemoryStream(temp);

            // Set Text
            textBox.Text = Converter.BytesToString(stream.ToArray());
        }
    }
}
